<template>
  <div class="role-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <el-button type="primary" @click="handleAddRole">新增角色</el-button>
        </div>
      </template>

      <!-- 搜索 -->
      <div class="search-container">
        <el-input
          v-model="searchForm.roleName"
          placeholder="请输入角色名称"
          style="width: 200px; margin-right: 10px"
        ></el-input>
        <el-button type="primary" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </div>

      <!-- 角色列表 -->
      <el-table
        v-loading="loading"
        :data="roleList"
        style="width: 100%; margin-top: 20px"
      >
        <el-table-column prop="id" label="ID" width="80"></el-table-column>
        <el-table-column
          prop="name"
          label="角色名称"
          width="180"
        ></el-table-column>
        <el-table-column prop="description" label="角色描述"></el-table-column>
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="180"
        ></el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="handleEditRole(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="success"
              size="small"
              @click="handleAssignPermission(scope.row)"
              >分配权限</el-button
            >
            <el-button
              type="danger"
              size="small"
              @click="handleDeleteRole(scope.row.id)"
              :disabled="scope.row.name === '管理员'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 新增/编辑角色弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="500px">
      <el-form
        ref="roleFormRef"
        :model="roleForm"
        :rules="roleRules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input
            v-model="roleForm.name"
            placeholder="请输入角色名称"
          ></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input
            v-model="roleForm.description"
            type="textarea"
            placeholder="请输入角色描述"
            :rows="3"
          ></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>

    <!-- 分配权限弹窗 -->
    <el-dialog v-model="permissionDialogVisible" title="分配权限" width="600px">
      <div class="permission-tree">
        <el-tree
          ref="permissionTreeRef"
          v-model:checkedKeys="checkedPermissions"
          :data="permissionTreeData"
          show-checkbox
          node-key="id"
          default-expand-all
        ></el-tree>
      </div>
      <template #footer>
        <el-button @click="permissionDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAssignPermissionSubmit"
          >确定</el-button
        >
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import type { TreeInstance } from "element-plus";

// 表格数据加载状态
const loading = ref(false);

// 搜索表单
const searchForm = reactive({
  roleName: "",
});

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 弹窗相关
const dialogVisible = ref(false);
const isEdit = ref(false);
const dialogTitle = ref("新增角色");
const roleFormRef = ref<FormInstance>();

// 角色表单数据
const roleForm = reactive({
  id: "",
  name: "",
  description: "",
});

// 表单验证规则
const roleRules = ref<FormRules>({
  name: [
    { required: true, message: "请输入角色名称", trigger: "blur" },
    { min: 2, max: 20, message: "长度在 2 到 20 个字符", trigger: "blur" },
  ],
  description: [
    { max: 200, message: "长度不能超过 200 个字符", trigger: "blur" },
  ],
});

// 角色列表数据
const roleList = ref<any[]>([]);

// 权限相关
const permissionDialogVisible = ref(false);
const permissionTreeRef = ref<TreeInstance>();
const currentRole = ref<any>(null);
const checkedPermissions = ref<any[]>([]);
const permissionTreeData = ref<any[]>([
  {
    id: 1,
    label: "系统管理",
    children: [
      { id: 101, label: "用户管理" },
      { id: 102, label: "角色管理" },
      { id: 103, label: "权限管理" },
    ],
  },
  {
    id: 2,
    label: "内容管理",
    children: [
      { id: 201, label: "文章管理" },
      { id: 202, label: "分类管理" },
    ],
  },
  {
    id: 3,
    label: "数据统计",
    children: [
      { id: 301, label: "用户统计" },
      { id: 302, label: "内容统计" },
    ],
  },
]);

// 获取角色列表
const getRoleList = () => {
  loading.value = true;
  // 模拟API请求
  setTimeout(() => {
    // 模拟数据
    const mockData = [
      {
        id: 1,
        name: "管理员",
        description: "系统管理员，拥有所有权限",
        createTime: "2023-01-01 10:00:00",
      },
      {
        id: 2,
        name: "编辑",
        description: "内容编辑，可以管理内容",
        createTime: "2023-01-02 14:30:00",
      },
      {
        id: 3,
        name: "运营",
        description: "数据运营，可以查看数据",
        createTime: "2023-01-03 09:15:00",
      },
      {
        id: 4,
        name: "客服",
        description: "客户服务，可以查看用户信息",
        createTime: "2023-01-04 16:45:00",
      },
      {
        id: 5,
        name: "普通用户",
        description: "基础用户权限",
        createTime: "2023-01-05 11:20:00",
      },
    ];

    // 筛选
    let filteredData = [...mockData];
    if (searchForm.roleName) {
      filteredData = filteredData.filter((item) =>
        item.name.includes(searchForm.roleName)
      );
    }

    // 分页
    const start = (pagination.currentPage - 1) * pagination.pageSize;
    const end = start + pagination.pageSize;
    roleList.value = filteredData.slice(start, end);
    pagination.total = filteredData.length;

    loading.value = false;
  }, 500);
};

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1;
  getRoleList();
};

// 重置搜索
const resetSearch = () => {
  searchForm.roleName = "";
  pagination.currentPage = 1;
  getRoleList();
};

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.pageSize = size;
  getRoleList();
};

// 页码变化
const handleCurrentChange = (current: number) => {
  pagination.currentPage = current;
  getRoleList();
};

// 新增角色
const handleAddRole = () => {
  isEdit.value = false;
  dialogTitle.value = "新增角色";
  // 重置表单
  Object.assign(roleForm, {
    id: "",
    name: "",
    description: "",
  });
  dialogVisible.value = true;
};

// 编辑角色
const handleEditRole = (row: any) => {
  isEdit.value = true;
  dialogTitle.value = "编辑角色";
  // 复制数据到表单
  Object.assign(roleForm, {
    id: row.id,
    name: row.name,
    description: row.description,
  });
  dialogVisible.value = true;
};

// 删除角色
const handleDeleteRole = (id: number) => {
  window.$ElMessageBox
    .confirm("确定要删除勾选的数据？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    })
    .then(() => {
      // 模拟删除请求
      loading.value = true;
      setTimeout(() => {
        window.$message.success("删除成功");
        getRoleList();
      }, 500);
    })
    .catch(() => {
      window.$message.info("已取消删除");
    });
};

// 分配权限
const handleAssignPermission = (row: any) => {
  currentRole.value = row;
  // 重置选中的权限
  checkedPermissions.value = [];
  // 模拟获取角色已有的权限
  // 在实际项目中，这里应该从API获取角色的权限
  if (row.name === "管理员") {
    // 管理员拥有所有权限
    checkedPermissions.value = [1, 101, 102, 103, 2, 201, 202, 3, 301, 302];
  } else if (row.name === "编辑") {
    // 编辑拥有内容管理相关权限
    checkedPermissions.value = [2, 201, 202];
  } else if (row.name === "运营") {
    // 运营拥有数据统计相关权限
    checkedPermissions.value = [3, 301, 302];
  }
  permissionDialogVisible.value = true;
};

// 提交表单
const handleSubmit = async () => {
  try {
    await roleFormRef.value?.validate();

    // 模拟提交请求
    loading.value = true;
    setTimeout(() => {
      loading.value = false;
      dialogVisible.value = false;
      window.$message.success(isEdit.value ? "编辑成功" : "新增成功");
      getRoleList();
    }, 500);
  } catch (error) {
    console.error("表单验证失败:", error);
  }
};

// 提交权限分配
const handleAssignPermissionSubmit = () => {
  // 模拟提交请求
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
    permissionDialogVisible.value = false;
    window.$message.success("权限分配成功");
  }, 500);
};

// 组件挂载时获取角色列表
onMounted(() => {
  getRoleList();
});
</script>

<style scoped lang="less">
.role-container {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-container {
    padding: 20px 0;
    display: flex;
    align-items: center;
  }

  .pagination-container {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }

  .permission-tree {
    max-height: 400px;
    overflow-y: auto;
    padding: 10px 0;
  }
}
</style>